<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="weaver.general.*" %>
<%@ page import="java.util.*" %>
<%@ page import="weaver.hrm.*" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page"/>
<jsp:useBean id="bb" class="weaver.general.BaseBean" scope="page"/>
<%
    /*
    *@Description: 资产购置-项目
    */
    int formid = Math.abs(Util.getIntValue(request.getParameter("formid")));//表单id
    Map<String, String> mainTableArray = new HashMap<String, String>(); //主表集合

    Map<String, String> detailTableArray2 = new HashMap<String, String>(); //明细2 票据信息 集合
	Map<String, String> detailTableArray3 = new HashMap<String, String>(); //明细3 费用分摊 集合

    formid = Math.abs(formid);
    String sql = " select b.id,fieldname,detailtable from workflow_billfield b ,workflow_base a where b.billid=-" + formid + " and a.formid=b.billid and (detailtable is null or detailtable = '') ";
    rs.execute(sql);
    while (rs.next()) {
        mainTableArray.put(Util.null2String(rs.getString("fieldname")).toLowerCase(), Util.null2String(rs.getString("id")));
    }

    String sql_detail = "select a.id,a.fieldname from workflow_billfield a,workflow_base b where a.BILLID=b.FORMID and a.billid=-" + formid + " and a.detailtable='formtable_main_" + formid + "_dt2'";
    rs.execute(sql_detail);
    while (rs.next()) {
        detailTableArray2.put(Util.null2String(rs.getString("fieldname")).toLowerCase(), Util.null2String(rs.getString("id")));
    }

	sql_detail = "select a.id,a.fieldname from workflow_billfield a,workflow_base b where a.BILLID=b.FORMID and a.billid=-" + formid + " and a.detailtable='formtable_main_" + formid + "_dt3'";
    rs.execute(sql_detail);
    while (rs.next()) {
        detailTableArray3.put(Util.null2String(rs.getString("fieldname")).toLowerCase(), Util.null2String(rs.getString("id")));
    }
%>
<style>
    .copybtn_p:hover {
        border: none;
        background: url(/wui/theme/ecology8/jquery/js/button/copy2_wev8.png) no-repeat;
        color: #333;
        width: 21px;
        height: 21px;
        text-align: left;
        cursor: pointer;
        padding-left: 10px;
        padding-top: 2px;
        margin-right: 5px;
        background-position: 50% 50%;
    }
    .copybtn_p {
        border: none;
        background: url(/wui/theme/ecology8/jquery/js/button/copy_wev8.png) no-repeat;
        color: #333;
        width: 21px;
        height: 21px;
        text-align: left;
        cursor: pointer;
        padding-left: 10px;
        padding-top: 2px;
        margin-right: 5px;
        background-position: 50% 50%;
    }
</style>
<script type="text/javascript">
    var endNode = 0;
    jQuery(document).ready(function () {
        jQuery('#div2button').append('<button type="button" class="copybtn_p"  id="$copybutton2$" name="copybutton2" title="复制" onclick="copyDetail()"></button>');
		jQuery("#\\\\$addbutton1\\\\$").click(function() {
			bindfee2(1);
		})
		bindfee2(2);

		jQuery("#\\\\$addbutton2\\\\$").click(function() {
			bindfee3(1);
		})
		bindfee3(2);

		jQuery("#field"+<%=mainTableArray.get("wrbtr")%>).change(function(){
			computeTTJE();
		})
		jQuery("#field"+<%=mainTableArray.get("hth")%>).change(function(){
			computeTTJE();
		})
        checkCustomize = function (){
            var flag2 = detail5();
            var flag3 = detail3();
            if (endNode > 0) {
                alert("请勿选择非末级节点");
                return false;
            } else if (!flag2) {
                return false;
            } else if (!flag3) {
                return false;
            } else {
                return true;
            }
        }
    })

	function bindfee2(value) {
        var indexnum0 = 0;
        if (document.getElementById("indexnum1")) {
            indexnum0 = document.getElementById("indexnum1").value * 1.0 - 1;
        }

        if (indexnum0 >= 0) {
            if (value == 1) { //当前添加的行
               addEvent(jQuery("#field"+<%=detailTableArray2.get("fpje")%> + "_" + indexnum0));
			   $("#"+$("#sehj span:first").attr("id")).bind('DOMNodeInserted',function(e){
						comput();
					});
			   addEvent(jQuery("#field"+<%=detailTableArray2.get("dmbtr")%> + "_" + indexnum0));
            } else if (value == 2) {//初始化
                jQuery("input[name='check_node_1']").each(function (i) {
                    var indexnum1 = this.value;
                    addEvent(jQuery("#field"+<%=detailTableArray2.get("fpje")%> + "_" + indexnum1));
					$("#"+$("#sehj span:first").attr("id")).bind('DOMNodeInserted',function(e){
						comput();
					});
					addEvent(jQuery("#field"+<%=detailTableArray2.get("dmbtr")%> + "_" + indexnum1));
                });
            }
        }
    }
    
    function bindfee3(value) {
        var indexnum0 = 0;
        if (document.getElementById("indexnum2")) {
            indexnum0 = document.getElementById("indexnum2").value * 1.0 - 1;
        }

        if (indexnum0 >= 0) {
            if (value == 1) { //当前添加的行
                jQuery("#field"+<%=detailTableArray3.get("gdzcxmkm")%>+"_" + indexnum0).bindPropertyChange(function () {
                    var gdzcxmkm = jQuery("#field"+<%=detailTableArray3.get("gdzcxmkm")%>+"_" + indexnum0).val();
                    if (!getGdzcxmkm(gdzcxmkm)) {
                        endNode++;
                    }

                });
                addEvent(jQuery("#field"+<%=detailTableArray3.get("je")%> + "_" + indexnum0));
            } else if (value == 2) {//初始化
                jQuery("#field"+<%=detailTableArray3.get("gdzcxmkm")%>+"_" + indexnum0).bindPropertyChange(function () {
                    var gdzcxmkm = jQuery("#field"+<%=detailTableArray3.get("gdzcxmkm")%>+"_" + indexnum0).val();
                    if (!getGdzcxmkm(gdzcxmkm)) {
                        endNode++;
                    }

                });
                jQuery("input[name='check_node_2']").each(function (i) {
                    var indexnum1 = this.value;
                    addEvent(jQuery("#field"+<%=detailTableArray3.get("je")%> + "_" + indexnum1));
                });
            }
        }
    }

	function addEvent($dom){
		$dom.change(function(){
			comput();
		});
	}
    function getGdzcxmkm(kmbm) {
        var flag = true;
        $.ajax({
            type: "POST",
            dataType: "json",
            async: false,
            url: "/interface/oacs/duss/getGdzcxmkm_Ajax.jsp",
            success: function (data) {
                var kms = data.kms;
                var arr = kms.split(",");
                for (var i = 0; i < arr.length; i++) {
                    if (kmbm == arr[i]) {
                        flag = false;
                    }
                }
            }
        })
        return flag;
    }

 function copyDetail(){
        jQuery("input[name='check_node_2']").each(function(){
            if(jQuery(this).attr("checked")=="checked"||jQuery(this).attr("checked")==true){
                addRow2(2);
                var old_rowIndex = jQuery(this).val();
                var new_rowIndex = jQuery("input[name='check_node_2']").last().val();
                jQuery("#oTable2").find("[name^='field'][name$='_"+old_rowIndex+"']").each(function(){
                    var fieldid = jQuery(this).attr("id");
                    var newfieldid = fieldid.replace("_"+old_rowIndex, "_"+new_rowIndex);
                    var val = jQuery(this).val();
                    var spanval = jQuery("#"+fieldid+"span").html();
                    jQuery("#"+newfieldid).val(val);
                    jQuery("#"+newfieldid+"span").html(spanval);

                    var _id = fieldid.substring(5, fieldid.indexOf("_"));
                    //wfbrowvaluechange('',_id,  new_rowIndex);
                });
            }
        });
    }

    function detail5() {
        var result = true;
        jQuery("input[name='check_node_1']").each(function (i) {
            var indexnum = jQuery(this).val();
            var fph = jQuery("#field" + <%=detailTableArray2.get("fpdm")%> +"_" + indexnum).val();
            console.log("------------------------");
            console.log("fph" + fph);
            $.ajax({
                type: "GET",
                cache: false,
                async: false,
                url: "/interface/lk/getNumber_ajax.jsp?fph=" + fph,
                success: function (str) {
                    str = str.replace(/^\s*|\s*$/g, "");
                    if (str == "1") {
                        result = confirm("票据信息中，第" + (indexnum * 1.00 + 1) + "行发票号与已申请流程发票号重复，是否继续提交");
                    }
                }
            })

        })

        return result;
    }
    function detail3() {
        var result = true;
        var bxzje=parseFloat(jQuery("#field" + <%=detailTableArray2.get("wrbtr")%>).val());//报销总金额
        var mx4jehj=parseFloat(jQuery("#field" + <%=detailTableArray2.get("ftje")%>).val());//明细4金额合计
        var hj=mx4jehj.toFixed(2);
        var fphj=jQuery("#field" + <%=detailTableArray2.get("fphj")%>).val();//发票合计
        if(mx4jehj>0){
            if(bxzje!=hj){
                alert("分摊总金额不等于报销总金额！");
                result=false;
            }
            if(fphj<bxzje){
                alert("发票金额小于报销金额！");
                result=false;
            }
        }
        return result;
    }
</script>

<script type="text/javascript">
/** 计算分摊的税
 *  分摊明细行税额=（分摊含税总额/票据含税总额）* 票据税额总额 * (分摊明细行含税/分摊含税总额)
 *					分摊明细行含税 * 票据税额总额 /票据含税总额
 */
function comput(){
	var fthsze = jQuery("#sumvalue"+<%=detailTableArray3.get("je")%>).val();
	var pjhsze = jQuery("#sumvalue"+<%=detailTableArray2.get("fpje")%>).val();
	var pjseze = jQuery("#sumvalue"+<%=detailTableArray2.get("dmbtr")%>).val();

	jQuery("input[name='check_node_2']").each(function(i){
		var indexnum = this.value

		var ftmxhhs = jQuery("#field"+<%=detailTableArray3.get("je")%> + "_" + indexnum).val();
		console.log("------------------------");
		console.log("票据税额总额 =" + pjseze);
		console.log("票据含税总额） =" + pjhsze);
		console.log("第"+indexnum+"分摊明细行含税 =" + ftmxhhs);

		var ftmxhse = accMul(ftmxhhs , pjseze / pjhsze).toFixed(2);
		console.log("分摊明细行税额 =" + ftmxhse);

		jQuery("#field"+<%=detailTableArray3.get("se")%>+"_"+indexnum+"span").text(ftmxhse);
		jQuery("#field"+<%=detailTableArray3.get("se")%>+"_"+indexnum).val(ftmxhse);
		jQuery("#field"+<%=detailTableArray3.get("se")%>+"_"+indexnum).change();

	})

	/** 如果分摊税额总额 != 票据的数额总额 , 把更改分摊的第一行的税额，使其相等 */
	var hsze = jQuery("#sumvalue"+<%=detailTableArray3.get("se")%>).val();//分摊含税总额
	var ce = accSub(accMul(fthsze,pjseze)/pjhsze,hsze);
	if(ce != 0){
		var value = jQuery("#field"+<%=detailTableArray3.get("se")%>+"_0").val();
		
		jQuery("#field"+<%=detailTableArray3.get("se")%>+"_0"+"span").text(accAdd(value,ce).toFixed(2));
		jQuery("#field"+<%=detailTableArray3.get("se")%>+"_0").val(accAdd(value,ce));
		jQuery("#field"+<%=detailTableArray3.get("se")%>+"_0").change();
		console.log("第一行数额进行差额调整:"+ce);
	}
}
function computeTTJE(){
	var hth = jQuery("#field"+<%=mainTableArray.get("hth")%>).val();
	if(hth == ""){
		jQuery("#field"+<%=mainTableArray.get("ttje")%>).val("");
		return;
	}
	$.ajax({
		type:"POST",
		cache: false,
		url: "/interface/lk/bzd_ajax.jsp?hth="+hth,
		success: function(str){
			var json = eval('(' + str + ')');
			/** 报销总金额 */
			var bxzje = jQuery("#field"+<%=mainTableArray.get("wrbtr")%>).val();
			console.log("报销金额:"+bxzje);
			/** 费用报支单金额  合同号对应的所有报支流程,主表报销金额之和 */
			var fybzdje = json.fybzdje;
			console.log("费用报支单金额:"+fybzdje);
			/** 费用报支未批金额 */
			var fyepje =json.fyepje;
			console.log("费用报支未批金额:"+fyepje);
			/** 已提请未付金额 */
			var ytqwfje = json.ytqwfje;
			console.log("已提请未付金额:"+ytqwfje);
			/** 以付金额 */
			var yfje = json.yfje;
			console.log("以付金额:"+yfje);
			
			/** TTJE=报销总金额+费用报支单金额+费用报支未批金额-已提请未付金额-已付款金额 */
			var ttje = accSub(accAdd( bxzje, accAdd(fybzdje,fyepje)),accAdd(ytqwfje,yfje) );
			console.log("TTJE:"+ttje);
			jQuery("#field"+<%=mainTableArray.get("ttje")%>).val(ttje);
		}
	})
}

</script>

<script type="text/javascript">
    //加法
    function accAdd(arg1,arg2){
        var r1,r2,m;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2));
        return (arg1*m+arg2*m)/m;
    }
    //减法
    function accSub(arg1,arg2){
        var r1,r2,m,n;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2));
        n=(r1>=r2)?r1:r2;
        return ((arg1*m-arg2*m)/m).toFixed(n);
    }
    //乘法
    function accMul(arg1, arg2) {
        var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
        try {
            m += s1.split(".")[1].length;
        }
        catch (e) {
        }
        try {
            m += s2.split(".")[1].length;
        }
        catch (e) {
        }
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    }
</script>